package com.ttc.mBackup.BackupImages;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;

import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

public class FileManager {
	public static String CreateInfoFile(String jsonString) {
		String filePath = "";

		try {
			filePath = Environment.getExternalStorageDirectory().toString()
					+ "/mBackup/info.jmb";
			saveFile(filePath, jsonString);

		} catch (Exception e) {
			Log.e("mediastore", e.getMessage());
		}

		return filePath;
	}
	
	public static boolean deleteInfoFile(){
		String filePath = Environment.getExternalStorageDirectory().toString()
		+ "/mBackup/info.jmb";
		return deleteFile(filePath);
	}

	public static boolean saveFile(String filePath, String content) {
		boolean result = true;

		File f = new File(filePath);
		if (f.exists())
			f.delete();

		FileWriter fw;
		try {
			f.createNewFile();
			fw = new FileWriter(f);
			
			fw.write(content);
			fw.flush();
			fw.close();

		} catch (IOException e1) {
			result = false;
			Log.i("mediastore", "Error at FileManager.saveFile: "
					+ e1.getMessage());
		}
		return result;
	}

	public static void getFolders(String path) {
		File f = new File("/sdcard/LOST.DIR");
		f.listFiles();
		Log.v("mediastore", f.getParent());
	}

	public static File[] getBackupFiles() {
		File[] files = null;
		try {
			String dirPath = Environment.getExternalStorageDirectory()
					.toString()
					+ "/mBackup";
			File dir = new File(dirPath);
			files = dir.listFiles(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String filename) {
					// TODO Auto-generated method stub
					return filename.endsWith(".zip");
				}
			});

		} catch (Exception e) {
			Log.e("mediastore", "Error at FileManager.getbackupFiles: "
					+ e.getMessage());
		}
		return files;
	}

	private static String[] readTextFile(String path) {
		String[] content = null;
		//		
		content = new String[2];
		

		File file;
		StringBuffer contents = new StringBuffer();
		BufferedReader reader = null;

		try {
			file = new File(path);
			reader = new BufferedReader(new FileReader(file));
			String text = null;

			String firstLine = reader.readLine();
			
			if (firstLine != null) {

				content[0] = firstLine;
				
				// repeat until all lines is read
				while ((text = reader.readLine()) != null) {
					contents.append(text).append(
							System.getProperty("line.separator"));
				}
				content[1] = contents.toString();
				
			}
			
		} catch (FileNotFoundException e) {
			Log.e("mediastore",
					"Error at FileManager.getTextFile: File not found - "
							+ e.getMessage());
		} catch (IOException e) {
			Log.e("mediastore", "Error at FileManager.getTextFile: IOEX - "
					+ e.getMessage());
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				Log.e("mediastore", "Error at FileManager.getTextFile: IOEX - "
						+ e.getMessage());
			}
		}
		return content;
	}

	public static String[] getInfoFileFromZip(String zipFilePath) {
		String[] content = null;
		try {
			File outputFile;
			ZipFile zipfile = new ZipFile(zipFilePath);
			ZipEntry entry = zipfile.getEntry("/sdcard/mBackup/info.jmb");
			String outputDir  = Environment.getExternalStorageDirectory()
					.toString() + "/mBackup";
			String fileName = "infotemp.tmp";
			if (entry != null) {
				
				
				outputFile = new File(outputDir, fileName);
				if (!outputFile.getParentFile().exists()) {
					createDir(outputFile.getParentFile());
				}
				if(!outputFile.exists()) outputFile.createNewFile();
				
				
				BufferedInputStream inputStream = new BufferedInputStream(zipfile
						.getInputStream(entry));
				BufferedOutputStream outputStream = new BufferedOutputStream(
						new FileOutputStream(outputFile));

				try {
					copy(inputStream, outputStream);
				} catch (Exception e) {
					Log.e("mediastore", "Error at FileManager.unzipEntry: "
							+ e.getMessage());
					
				} finally {
					outputStream.close();
					inputStream.close();
				}
				

				if(outputFile!=null) content = readTextFile(outputFile.getPath());
			}

		} catch (Exception e) {
			Log.e("mediastore", "Error at FileManager.getInfoFileFromZip: "
					+ e.getMessage());
		}
		return content;
	}

	public static boolean deleteTempFile(){
		String filename  = Environment.getExternalStorageDirectory()
		.toString() + "/mBackup" + "/infotemp.tmp";
		return deleteFile(filename);
	}
	
	public static boolean deleteFile(String path){
		boolean result = true;
		try{
			File f = new File(path);
			return f.delete();
		}catch (Exception e) {
			Log.e("mediastore", "Error at FileManager.deleteFile: " + e.getMessage());
		}
		return result;
	}

	public static void createDir(File dir) {
		if (dir.exists()) {
			return;
		}

		if (!dir.mkdirs()) {
			throw new RuntimeException("Can not create dir " + dir);
		}
	}

	public static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[1024];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}
	
	public static long getFileSize(ArrayList<String> paths){
		long size = 0;
		File f;
		try{
		for (String p : paths) {
			f = new File(p);
			size += f.length();
		}
		}catch (Exception e) {
			Log.v("mediastore", "Error at FileManager.getFileSize: " + e.getMessage());
			return 0;
		}
		return size;
	}
	public static double getFreeSpaceOnSDCard(){
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
		double sdAvailSize = (double)stat.getAvailableBlocks() *(double)stat.getBlockSize();

		return sdAvailSize; //in byte
	}
	
	public static boolean checkEnoughMemory(ArrayList<String> paths){
		if(getFileSize(paths) > getFreeSpaceOnSDCard())
			return false;
		return true;
	}

}
